import numpy as np
import cv2

# 定义每一个数字对应的字段
DIGITS_LOOKUP = {
    (1, 1, 1, 0, 1, 1, 1): 0,
    (0, 0, 1, 0, 0, 1, 0): 1,
    (1, 0, 1, 1, 1, 0, 1): 2,
    (1, 0, 1, 1, 0, 1, 1): 3,
    (0, 1, 1, 1, 0, 1, 0): 4,
    (1, 1, 0, 1, 0, 1, 1): 5,
    (1, 1, 0, 1, 1, 1, 1): 6,
    (1, 0, 1, 0, 0, 1, 0): 7,
    (1, 1, 1, 1, 1, 1, 1): 8,
    (1, 1, 1, 1, 0, 1, 1): 9
}

img = cv2.imread('IMG_1741.JPG')
new_size = (1200, 800)
img = cv2.resize(img, new_size)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
_, thresh = cv2.threshold(gray, 90, 255, cv2.THRESH_BINARY_INV)
# 寻找轮廓
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

img_copy = img.copy()
min_distance = 20
selected_contours = []

# 筛选轮廓并过滤小面积区域
for cnt in contours:
    x, y, w, h = cv2.minAreaRect(cnt)
    if w * h < 100:  # 过滤面积过小的轮廓
        continue
    valid = True
    for (sx, sy, sw, sh) in selected_contours:
        if (abs(x - sx) < min_distance and abs(y - sy) < min_distance):
            valid = False
            break
    if valid:
        selected_contours.append((x, y, w, h))

for cnt in selected_contours:
    x, y, w, h = cnt
    area = w * h
    if area > 100:
        print("xywh", x, y, w, h)
        print("矩形面积：", area)
        roi = thresh[y:y + h, x:x + w]
        cv2.imshow("ROI", roi)
        cv2.waitKey(0)
        print("矩形面积：", area)

cv2.imshow("Output", thresh)
digits = []
for (x, y, w, h) in selected_contours:
    roi = thresh[y:y+h, x:x+w]  # 使用二值化后的thresh图像
    (roiH, roiW) = roi.shape
    debug_img = cv2.cvtColor(roi, cv2.COLOR_GRAY2BGR)

    # 根据ROI尺寸动态调整段区域
    dW = int(roiW * 0.25)
    dH = int(roiH * 0.15)
    dHC = int(roiH * 0.05)
    
    # 定义七段管区域
    segments = [
        ((0, 0), (roiW, dH)),                  # 上
        ((0, 0), (dW, roiH//2)),               # 左上
        ((roiW-dW, 0), (roiW, roiH//2)),       # 右上
        ((0, (roiH//2)-dHC), (roiW, (roiH//2)+dHC)), # 中
        ((0, roiH//2), (dW, roiH)),            # 左下
        ((roiW-dW, roiH//2), (roiW, roiH)),    # 右下
        ((0, roiH-dH), (roiW, roiH))           # 下
    ]
    
    on = [0] * 7
    for i, ((xA, yA), (xB, yB)) in enumerate(segments):
        segROI = roi[yA:yB, xA:xB]
        total = cv2.countNonZero(segROI)
        area = (xB - xA) * (yB - yA)
        if area > 0 and (total / float(area)) > 0.3:
            on[i] = 1
    digit = DIGITS_LOOKUP.get(tuple(on), None)
    if digit is not None:
        digits.append(digit)
        cv2.rectangle(img_copy, (x, y), (x+w, y+h), (0, 255, 0), 1)
        cv2.putText(img_copy, str(digit), (x-10, y-10), 
                    cv2.FONT_HERSHEY_SIMPLEX, 0.65, (0, 255, 0), 2)
print(len(digits))
cv2.imshow("Output", img_copy)
cv2.waitKey(0)